import ajax from 'uni-ajax'
import env from '@/config/env'
import { platform } from '@/utils/platform'
import useUserStore from '@/store/user'
// 创建请求实例
const instance = ajax.create({
  // 初始配置
  baseURL: env.baseUrl + "/jeecg-system",
  timeout: 30000,
  header: {
    'User-Port': platform,
  },
})
// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    // 在发送请求前做些什么
    const userStore = useUserStore()
    if(userStore.token){
      config.header['X-Access-Token'] = userStore.token
      config.header['Authorization'] = "Bearer " + userStore.token
    }
    // config.header['X-Tenant-Id'] = '1000';
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    if (response.data.code === 200) return response.data
    return Promise.reject(response.data)
  },
  error => {
    // 对响应错误做些什么
    switch (error.statusCode) {
      case 500:
        uni.showToast({
          title: '服务器异常',
          icon: 'none',
          mask: true,
          duration: 1000,
          complete: () => {
            setTimeout(() => {
              uni.reLaunch({
                url: `/pages/index/index`,
              })
            }, 1000)
          },
        })
        break
      default:
        // #ifdef H5
        const userStore = useUserStore()
        userStore.token = ""
        uni.showToast({
          title: '登录过期，重新登录',
          icon: 'none',
          mask: true,
          duration: 1000,
          complete: () => {
            setTimeout(() => {
              uni.reLaunch({
                url: `/pages/login/login`,
              })
            }, 1000)
          },
        })
        // #endif

        // #ifdef MP-TOUTIAO
        uni.showToast({
          title: '服务器异常',
          icon: 'none',
          mask: true,
          duration: 1000,
          complete: () => {
            setTimeout(() => {
              uni.reLaunch({
                url: `/pages/index/index`,
              })
            }, 1000)
          },
        })
        // #endif
    }
    return Promise.reject(error)
  }
)

// 导出 create 创建后的实例
export default instance
